package com.greate.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.benmanes.caffeine.cache.CacheLoader;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.greate.community.dao.DiscussPostMapper;
import com.greate.community.entity.*;
import com.greate.community.event.EventProducer;
import com.greate.community.service.*;
import com.greate.community.util.*;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 帖子相关
 */
@Service
public class DiscussPostServiceImpl implements DiscussPostService {

    private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

    @Autowired
    private DiscussPostMapper discussPostMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private SectionService sectionService;

    @Autowired
    private EventProducer eventProducer;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${caffeine.posts.max-size}")
    private int maxSize;

    @Value("${caffeine.posts.expire-seconds}")
    private int expireSeconds;

    // 网站域名
    @Value("${community.path.domain}")
    private String domain;

    // 项目名(访问路径)
    @Value("${server.servlet.context-path}")
    private String contextPath;

    // editorMd 图片上传地址
    @Value("${community.path.editormdUploadPath}")
    private String editormdUploadPath;

    @Value("${community.path.videoUploadPath}")
    private String videoUploadPath;

    // 热帖列表的本地缓存
    // key - offset(每页的起始索引):limit(每页显示多少条数据)
    private LoadingCache<String, List<DiscussPost>> postListCache;

    // 帖子总数的本地缓存
    // key - userId(其实就是0,表示查询的是所有用户. 对特定用户的查询不启用缓存）
    private LoadingCache<Integer, Integer> postRowsCache;

    /**
     * 初始化本地缓存 Caffeine
     */
    @PostConstruct
    public void init() {
        // 初始化热帖列表缓存
        postListCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<String, List<DiscussPost>>() {
                    // 如果缓存Caffeine中没有数据，告诉缓存如何去数据库中查数据，再装到缓存中
                    @Nullable
                    @Override
                    public List<DiscussPost> load(@NonNull String key) throws Exception {
                        if (key == null || key.length() == 0) {
                            throw new IllegalArgumentException("参数错误");
                        }

                        String[] params = key.split(":");
                        if (params == null || params.length != 2) {
                            throw new IllegalArgumentException("参数错误");
                        }

                        int offset = Integer.valueOf(params[0]);
                        int limit = Integer.valueOf(params[1]);

                        // 此处可以再访问二级缓存 Redis

                        logger.debug("load post list from DB");
                        return discussPostMapper.selectDiscussPosts(0, offset, limit, 0, 1);
                    }
                });

        // 初始化帖子总数缓存
        postRowsCache = Caffeine.newBuilder()
                .maximumSize(maxSize)
                .expireAfterWrite(expireSeconds, TimeUnit.SECONDS)
                .build(new CacheLoader<Integer, Integer>() {
                    @Nullable
                    @Override
                    public Integer load(@NonNull Integer key) throws Exception {
                        logger.debug("load post rows from DB");
                        return discussPostMapper.selectDiscussPostRows(key, 0);
                    }
                });
    }


    /**
     * 分页查询讨论帖信息
     *
     * @param userId 当传入的 userId = 0 时查找所有用户的帖子
     *               当传入的 userId != 0 时，查找该指定用户的帖子
     * @param offset 每页的起始索引
     * @param limit  每页显示多少条数据
     * @param orderMode  排行模式(若传入 1, 则按照热度来排序)
     * @return
     */
    public List<DiscussPost> findDiscussPosts (int userId, int offset, int limit, int sectionId, int orderMode) {
//         查询本地缓存(当查询的是所有用户的帖子并且按照热度排序时)
        if (userId == 0 && orderMode == 1 && sectionId == 0) {
            return postListCache.get(offset + ":" + limit);
        }
        // 查询数据库
        logger.debug("load post list from DB");
        return discussPostMapper.selectDiscussPosts(userId, offset, limit, sectionId, orderMode);
    }

    /**
     * 查询讨论贴的个数
     * @param userId 当传入的 userId = 0 时计算所有用户的帖子总数
     *               当传入的 userId ！= 0 时计算该指定用户的帖子总数
     * @return
     */
    public int findDiscussPostRows (int userId, int sectionId) {
        // 查询本地缓存(当查询的是所有用户的帖子总数时)
        if (userId == 0 && sectionId == 0) {
            return postRowsCache.get(userId);
        }
        // 查询数据库
        logger.debug("load post rows from DB");
        return discussPostMapper.selectDiscussPostRows(userId, sectionId);
    }

    /**
     * 添加视频贴
     * @param title
     * @param file
     * @return
     */
    @Override
    public void addVideo(String title, Long section, MultipartFile file) {
        String url = null; // 视频访问地址
        if (StringUtils.isEmpty(title)){
            throw new BusinessException(BusCodeEnum.MISSING_TITLE);
        }
        try {
            // 获取上传文件的名称
            String trueFileName = file.getOriginalFilename();
            String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
            String fileName = CommunityUtil.generateUUID() + suffix;

            // 视频存储路径
            File dest = new File(videoUploadPath + "/" + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            // 视频访问地址
            url = domain + contextPath + "/video-upload/" + fileName;
            addDiscussPost(title, section, url, 1);
            // 保存视频到存储路径
            file.transferTo(dest);
        } catch (Exception e) {
            throw new BusinessException(BusCodeEnum.ERROR_SAVE_ERROR);
        }
    }

    /**
     * 添加帖子
     * @param title
     * @param content
     * @return
     */
    public void addDiscussPost(String title, Long section, String content, Integer kind) {
        User user = hostHolder.getUser();
        if (user == null) {
            throw new BusinessException(BusCodeEnum.NO_LOGGING_USER);
        }
        if (StringUtils.isEmpty(title)){
            throw new BusinessException(BusCodeEnum.MISSING_TITLE);
        }
        DiscussPost discussPost = new DiscussPost();
        discussPost.setUserId(user.getId());
        discussPost.setSectionId(section);
        discussPost.setTitle(title);
        discussPost.setKind(kind);
        if (kind.equals(0)){
            discussPost.setContent(StringFilterUtils.filterSpecialCharacters(content));//过滤特殊字符
        } else {
            discussPost.setContent(content);
        }
        discussPost.setCreateTime(new Date());

        // 转义 HTML 标记，防止在 HTML 标签中注入攻击语句;过滤敏感词
        discussPost.setTitle(HtmlUtils.htmlEscape(discussPost.getTitle()));
        discussPost.setTitle(sensitiveFilter.filter(discussPost.getTitle()));
        if (discussPost.getKind() == 0){
            discussPost.setContent(HtmlUtils.htmlEscape(discussPost.getContent()));
            discussPost.setContent(sensitiveFilter.filter(discussPost.getContent()));
        }

        addDiscussPost(discussPost);

        // 计算帖子分数
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, discussPost.getId());
    }

    @Override
    public void addDiscussPost(DiscussPost post) {

        discussPostMapper.insertDiscussPost(post);
        // 触发发帖事件，通过消息队列将其存入 Elasticsearch 服务器
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(post.getUserId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId());
        eventProducer.fireEvent(event);
    }


    /**
     * 根据 id 查询帖子
     * @param id
     * @return
     */
    public DiscussPost findDiscussPostById(int id) {
        return discussPostMapper.selectDiscussPostById(id);
    }

    /**
     * 修改帖子的评论数量
     * @param id 帖子 id
     * @param commentCount
     * @return
     */
    public int updateCommentCount(int id, int commentCount) {
        return discussPostMapper.updateCommentCount(id, commentCount);
    }

    /**
     * 修改帖子类型：0-普通; 1-置顶;
     * @param id
     * @param type
     * @return
     */
    public int updateType(int id, int type) {
        return discussPostMapper.updateType(id, type);
    }

    /**
     * 修改帖子状态：0-正常; 1-精华; 2-拉黑;
     * @param id
     * @param status
     * @return
     */
    public int updateStatus(int id, int status) {
        return discussPostMapper.updateStatus(id, status);
    }

    /**
     * 修改帖子分数
     * @param id
     * @param score
     * @return
     */
    public int updateScore(int id, double score) {
        return discussPostMapper.updateScore(id, score);
    }

    @Override
        public String uploadMdPic(MultipartFile file) {
        String url = null; // 图片访问地址
        try {
            // 获取上传文件的名称
            String trueFileName = file.getOriginalFilename();
            String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
            String fileName = CommunityUtil.generateUUID() + suffix;

            // 图片存储路径
            File dest = new File(editormdUploadPath + "/" + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            // 保存图片到存储路径
            file.transferTo(dest);

            // 图片访问地址
            url = domain + contextPath + "/editor-md-upload/" + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return CommunityUtil.getEditorMdJSONString(0, "上传失败", url);
        }
        return CommunityUtil.getEditorMdJSONString(1, "上传成功", url);
    }

    @Override
    public int getPostsDisabledRows() {
        return discussPostMapper.selectPostsDisabledRows();
    }

    @Override
    public List<DiscussPost> getPostsDisabled(int offset, int limit) {
        LambdaQueryWrapper<DiscussPost> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DiscussPost::getStatus, 1);
        return discussPostMapper.selectDisabledPosts(offset, limit);
    }


}
